/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAMaterialViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 09/08/13.
//  Copyright (c) 2013 Redia A/S. All rights reserved.
//

#import "BAAbstractViewController.h"
#import "BAAddReservationViewController.h"
#import "BACoverUrl.h"
#import "BACoverUrlAndAvailabilityMemoryCache.h"
#import "BAFlyoutMenuViewController.h"
#import "BAFullRecord.h"
#import "BALibrarySettings.h"
#import "BAMagazineTableViewController.h"
#import "BAMaterialViewController.h"
#import "BAPatronSettings.h"
#import "BARelatedMaterialsTableViewController.h"
#import "BARPCManager.h"
#import "BATabSwitchViewController.h"
#import "BAUtils.h"
#import "BAWebBrowserViewController.h"
#import "BARootViewController.h"
#import "InfoGalleriImageUrlUtils.h"
#import "LazyLoadManager.h"

#import <QuartzCore/QuartzCore.h>


#ifdef BA_IMF_BUILD
#import "IMFLocationManager.h"
#import "IMFPackageEditManager.h"
#import "IMFAddMaterialToIMFPackageViewController.h"
#endif


#define BA_MATERIAL_VIEW_RESERVE_BUTTON_DEFAULT_WIDTH ((RD_IS_IPAD) ? 166 : 77)

@interface BAMaterialViewController () {
    BARelatedMaterialsTableViewController* relatedMaterialsTableViewController;
    BAAbstractViewController* recordDetailsViewController;
    BATabSwitchViewController* myTabSwitch;
    BAAbstractViewController* abstractInMainViewIpad;
    NSLayoutConstraint *mCoverImageAspectRatioConstraint;
}

@property (weak, nonatomic) IBOutlet UIButton *addMaterialToIMFPackageButton;
@property (weak, nonatomic) IBOutlet UILabel *availLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bookCoverImageView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *authorLabel;
@property (weak, nonatomic) IBOutlet UILabel *detailsLabel;
@property (weak, nonatomic) IBOutlet UIButton *reserveButton;
@property (weak, nonatomic) IBOutlet UIView *tabSwitchView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *reserveButtonWidth;
@property (weak, nonatomic) IBOutlet UIView *tabSwitchViewView;
@property (weak, nonatomic) IBOutlet UIView *bottomHalfView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *bottomLoadingIndicator;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHalfViewHeight;

//ipad specific outlets
@property (weak, nonatomic) IBOutlet UIView *abstractViewForIPad;

@end

@implementation BAMaterialViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    
    BA_LABEL_SET_FONT_LIGHT(self.availLabel);
    BA_LABEL_SET_FONT_REGULAR(self.titleLabel);
    BA_LABEL_SET_FONT_REGULAR(self.authorLabel);
    if (RD_IS_IPAD) {
        BA_LABEL_SET_FONT_LIGHT(self.detailsLabel);
    } else {
        BA_LABEL_SET_FONT_REGULAR(self.detailsLabel);
    }
    
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)

    [self showReservationButton:NO]; //was: self.reserveButtonWidth.constant = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didRemoveResource:)
                                                 name:IMF_DID_REMOVE_RESOURCE
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didAddResource:)
                                                 name:IMF_DID_ADD_RESOURCE
                                               object:nil];

    
    if (RD_IS_IPAD) {
        abstractInMainViewIpad = [BAAbstractViewController new];
        [self addChildViewController:abstractInMainViewIpad];
        abstractInMainViewIpad.view.frame = self.abstractViewForIPad.bounds;
        [self.abstractViewForIPad addSubview:abstractInMainViewIpad.view];
        [BAUtils setViewToFillParent:abstractInMainViewIpad.view];
    }
    
}

- (void) didAddResource:(NSNotification *)notification{
    NSString *identifier = [notification object];
    if ([theRecord.identifier isEqual:identifier]) {
        [self.reserveButton setTitle:@"FJERN" forState:UIControlStateNormal];
    }
    
}

- (void) didRemoveResource:(NSNotification *)notification{
    NSString *identifier = [notification object];
    if ([theRecord.identifier isEqual:identifier]) {
        [self.reserveButton setTitle:@"TILFØJ" forState:UIControlStateNormal];
    }
}


-(void)createTabSwitchViews
{
    myTabSwitch = [[BATabSwitchViewController alloc] initWithSelectionColor:nil unselectionColor:[UIColor colorWithWhite:0.85 alpha:1]];
    [myTabSwitch.view setFrame:self.tabSwitchView.bounds];
    [self.tabSwitchView addSubview:myTabSwitch.view];
    [BAUtils setViewToFillParent:myTabSwitch.view];
    
    [myTabSwitch setTitleStrings:@[@"MERE OM",@"DETALJER"]];
    [self addChildViewController:myTabSwitch];
    myTabSwitch.delegate = self;
    
    [self showRecordDetails];
    [self showRelatedList];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self enableUserInteraction];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    if ([self.navigationController.viewControllers count] > 1) {
        UIViewController *secondFromTheTop = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
        if (secondFromTheTop == self) {
            // This view may become visible again - don't cancel ongoing requests.
            return;
        }
    }
    
    [BARPCManager closeConnectionsForView:self];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (theFullRecord.isERessource && ![[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]){
        return;
    }
    
#ifdef BA_IMF_BUILD
    if([IMFPackageEditManager instance].isEditingPackage) {
        if([[IMFPackageEditManager instance] hasResourceWithIdentifier:theRecord.identifier]) {
            [self.reserveButton setTitle:@"FJERN" forState:UIControlStateNormal];
        } else {
            [self.reserveButton setTitle:@"TILFØJ" forState:UIControlStateNormal];
        }
        [self showReservationButton:YES];
    } else {
        if([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary] && [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
            [self.reserveButton setTitle:@"RESERVER" forState:UIControlStateNormal];
        } else if([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
            if([[IMFPackageEditManager instance] hasResourceWithIdentifier:theRecord.identifier]) {
                [self.reserveButton setTitle:@"FJERN" forState:UIControlStateNormal];
            } else {
                [self.reserveButton setTitle:@"TILFØJ" forState:UIControlStateNormal];
            }
            [self showReservationButton:YES];

        } else if([[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
            //it is an error if we land here, this case should only be active when showing in LibrarianMaterialViewController
        } else {
            [self.reserveButton setTitle:@"RESERVER" forState:UIControlStateNormal];
        }
    }
#endif
    
}


- (void)tabSwitchSelected:(int)index withTitle:(NSString *)title
{
    if (index==0) {
        [self showRelatedList];
    } else {
        [self showRecordDetails];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setTitleText:(NSString*)titleText andAuthorText:(NSArray*)creators
{
    self.titleLabel.text = titleText;

    CGRect titlesize = [self.titleLabel textRectForBounds:self.titleLabel.frame limitedToNumberOfLines:3];
    DLog(@"titlesize: %@",NSStringFromCGRect(titlesize));
    if (titlesize.size.height<20) {
        self.authorLabel.numberOfLines = 3;
    } else if (titlesize.size.height<40) {
        self.authorLabel.numberOfLines = 2;
    }

    NSString* authors = [BAUtils makeCommaSeparatedStringFromStrings:creators];
    
    if ([authors length]>0) {
        authors = [@"AF: " stringByAppendingString:[authors uppercaseString]];
    } else {
        authors = @""; //to avoid the string NULL
    }
    self.authorLabel.text = authors;
    
 
}

-(void)showReservationButton:(BOOL)doShow
{
    if (doShow) {
        self.reserveButtonWidth.constant = BA_MATERIAL_VIEW_RESERVE_BUTTON_DEFAULT_WIDTH;
    } else {
        self.reserveButtonWidth.constant = 0;
    }
}   

- (void)updateAvailability:(BAAvailability*)availability
{
    if (![[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
        //only update showing reserve button when not IMF editor
        if (availability != nil && availability.isReservable && [availability.reservationId length] > 0) {
            [self showReservationButton:YES]; //was: self.reserveButtonWidth.constant = BA_MATERIAL_VIEW_RESERVE_BUTTON_DEFAULT_WIDTH;
        } else if (theFullRecord.isERessource) {
            [self showReservationButton:YES]; //was: self.reserveButtonWidth.constant = BA_MATERIAL_VIEW_RESERVE_BUTTON_DEFAULT_WIDTH;
            [self.reserveButton setTitle:@"GÅ TIL" forState:UIControlStateNormal];
            // transparent bagground
            // Text color = "text grå"
            [self.reserveButton removeTarget:self action:@selector(reserveButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            [self.reserveButton addTarget:self action:@selector(goToEResourceButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [self showReservationButton:NO]; //was: self.reserveButtonWidth.constant = 0;
        }
    }
    
    //update avail label
    if (availability != nil && availability.isReservable && [availability.reservationId length] > 0) {
        [self.availLabel setHidden:NO];
    } else if (theFullRecord.isERessource) {
        [self.availLabel setHidden:NO];
        self.availLabel.text = @"Online";
    }
    
    if (!theFullRecord.isERessource) {
        if (availability != nil && availability.isReservable && [availability.homeAt count] > 0) {
            self.availLabel.text = @"Hjemme";
        }
        else if (availability!= nil && availability.isReservable && [availability.homeAt count] == 0) {
            self.availLabel.text = @"Udlånt";
        }
        else {
            //this means "not to be borrowed"
            //self.availLabel.text = @"Kun på bibl.";
            self.availLabel.hidden=YES;
        }
    }
}

-(void)showFullRecord:(BAFullRecord *)fullrec withCoverUrl:(NSString *)coverUrl currentImage:(UIImage *)currentImage availability:(BAAvailability *)availability
{
    if (fullrec!=nil) {
        theFullRecord = fullrec;
        BARecord* rec = [BARecord recordFromFullRecord:fullrec];
        [self showRecord:rec withCoverUrl:coverUrl currentImage:currentImage availability:availability];
    }
}

- (void)showRecord:(BARecord *)rec withCoverUrl:(NSString *)coverUrl currentImage:(UIImage *)currentImage availability:(BAAvailability*)availability
{
    theRecord = rec;
    
    [self view];
    
    [self setTitleText:rec.title andAuthorText:rec.creators];
    self.detailsLabel.text = rec.type;
   
    if (availability == nil) {
        availability = [[BACoverUrlAndAvailabilityMemoryCache instance] getAvailabilityForIdentifier:theRecord.identifier];
    }
    [self updateAvailability:availability];
    
    if (currentImage/* && BA_IS_IPHONE*/) {
        self.bookCoverImageView.image = currentImage;
        [self setCoverImageAspectRatioConstraintForSize:currentImage.size];
    } else {
        UIImage* icon_image = [[BALibrarySettings instance] getIconForMaterialType:rec.type
                                                             contextIdentifier:BATypeIconContextBAppsMaterialView
                                                                         color:[UIColor colorWithWhite:0.65 alpha:1]];
        self.bookCoverImageView.image = icon_image;
    }
    
    
    if (theFullRecord == nil) {
        [BARPCManager getObjectsAsyncFromView:self
                                          ids:@[rec.identifier]
                           includeHoldingInfo:YES
                                  resultBlock:^(NSDictionary *result) {
                                      DLog(@"result %@",result);
                                      
                                      BAStandardResultObject* rec_std_result = [result objectForKey:rec.identifier]; //the results are ordered in the dictionary by keys from the record identifier
                                      if (rec_std_result.result) {
                                          BAFullRecord* full_record = rec_std_result.parsedData;
                                          
                                          theFullRecord = full_record;
                                          [self finishedLoadingFullRecord];
                                      }
                                      [relatedMaterialsTableViewController setAvailability:theFullRecord.availability];
                                  } errorBlock:^(int code, NSString *error) {
                                      DLog(@"error: %@, %d",error,code);
                                      [relatedMaterialsTableViewController setAvailability:nil];
                                  }];
    }
    else {
        [relatedMaterialsTableViewController setAvailability:theFullRecord.availability];
        [self finishedLoadingFullRecord];
    }


    if (coverUrl == nil) {
        coverUrl = [[BACoverUrlAndAvailabilityMemoryCache instance] getCoverUrlForIdentifier:theRecord.identifier].url;
    }
    if (coverUrl && [coverUrl length]>0) {
        [self fetchCoverUrl:coverUrl];
    } else {
        if (rec.identifier != nil) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNewCoverUrls:) name:BA_COVER_URL_CACHE_COVER_URLS_ARRIVED object:nil];
            [[BACoverUrlAndAvailabilityMemoryCache instance] fetchCoverUrlsForIdentifiers:@[rec.identifier]];
            
        }
//        [BARPCManager getCoverUrlsAsyncFromView:self
//                                coverUrlQueries:@[rec.identifier]
//                                    resultBlock:^(NSDictionary* result) {
//                                        BAStandardResultObject* std_result_for_coverurls = [result objectForKey:rec.identifier];
//                                        
//                                        if (std_result_for_coverurls != nil && std_result_for_coverurls.result) {
//                                            BACoverUrl* coverurl_info = std_result_for_coverurls.parsedData;
//                                            if (coverurl_info && [coverurl_info.url length]>0) {
//                                                [self fetchCoverUrl:coverurl_info.url];
//                                            }
//                                        }
//                                    }
//                                     errorBlock:^(int errorCode, NSString *errorMessage) {
//                                         DLog(@"error fetching coverurl %d %@",errorCode, errorMessage);
//                                     }];
        
    }
    
    
    

    [self createTabSwitchViews];
    [relatedMaterialsTableViewController setRecord:rec];

}

- (void)showMagazineFullRecord:(BAFullRecord*)fullRecord andAvailability:(BAAvailability*)availability withVolumeTitle:(NSString*)volumeTitle andShortVolumeTitle:(NSString *)shortVolumeTitle
{
    theFullRecord = fullRecord;
    //theAvailability = availability;
    //theTitle = title;
    
    [self view];
    
    UIImage* icon_image = [[BALibrarySettings instance] getIconForMaterialType:fullRecord.type
                                                             contextIdentifier:BATypeIconContextBAppsMaterialView
                                                                         color:[UIColor colorWithWhite:0.65 alpha:1]];
    self.bookCoverImageView.image = icon_image;

    
    [self updateTextFields];
    
    if (theFullRecord.availability) {
        [self updateAvailability:theFullRecord.availability];
    }

    [self.bottomLoadingIndicator stopAnimating];

    [self setupMagazineViewWithAvailability:availability withVolumeTitle:volumeTitle andShortVolumeTitle:shortVolumeTitle];
    
    if (RD_IS_IPAD) {
        if (abstractInMainViewIpad!=nil) {
            [abstractInMainViewIpad setFullRecord:fullRecord];
        }
    }
    
}

-(void)setupMagazineViewWithAvailability:(BAAvailability*)availability withVolumeTitle:(NSString*)volumeTitle andShortVolumeTitle:(NSString *)shortVolumeTitle
{
    if (RD_IS_IPAD) {
        if (relatedMaterialsTableViewController!=nil) {
            [relatedMaterialsTableViewController.view removeFromSuperview];
            [relatedMaterialsTableViewController removeFromParentViewController];
            relatedMaterialsTableViewController=nil;
        }
        /*
        if (abstractInMainViewIpad!=nil) {
            [abstractInMainViewIpad.view removeFromSuperview];
            [abstractInMainViewIpad removeFromParentViewController];
            abstractInMainViewIpad=nil;
        }*/
        self.bottomHalfViewHeight.constant = 238; //make bottom space bigger for magazine table
        
    } else {
        //iPhone
        
        if (relatedMaterialsTableViewController!=nil) {
            [relatedMaterialsTableViewController.view removeFromSuperview];
            [relatedMaterialsTableViewController removeFromParentViewController];
            relatedMaterialsTableViewController=nil;
        }
        if (recordDetailsViewController!=nil) {
            [recordDetailsViewController.view removeFromSuperview];
            [recordDetailsViewController removeFromParentViewController];
            recordDetailsViewController=nil;
        }
        if (myTabSwitch!=nil) {
            [myTabSwitch.view removeFromSuperview];
            [myTabSwitch removeFromParentViewController];
            myTabSwitch=nil;
        }
    }
    BAMagazineTableViewController* magazinetable = [BAMagazineTableViewController new];
    [self addChildViewController:magazinetable];
    [self.bottomHalfView addSubview:magazinetable.view];
    [BAUtils setViewToFillParent:magazinetable.view];
    [magazinetable setAvailability:availability andFullRecord:theFullRecord withVolumeTitle:volumeTitle andShortVolumeTitle:shortVolumeTitle];
}



- (void)finishedLoadingFullRecord
{
    [self updateTextFields];
    
    if (theFullRecord.availability) {
        [self updateAvailability:theFullRecord.availability];
    }
    
    [self.bottomLoadingIndicator stopAnimating];
    
    if([theFullRecord.availability.holdingContainers count] == 0) {
        //not magazine
        if (myTabSwitch==nil) {
            [self createTabSwitchViews];
        }
        [recordDetailsViewController setFullRecord:theFullRecord];
        //already done: [relatedMaterialsTableViewController setRecord:theRecord];
        
        if (RD_IS_IPAD) {
            [abstractInMainViewIpad setFullRecord:theFullRecord];
        }
        
    } else {
        //is magazine
        [self setupMagazineViewWithAvailability:theFullRecord.availability withVolumeTitle:theFullRecord.title andShortVolumeTitle:theFullRecord.title];
        if (RD_IS_IPAD) {
            [abstractInMainViewIpad setFullRecord:theFullRecord];
        }

    }
}

-(void)updateTextFields
{
    [self setTitleText:theFullRecord.title andAuthorText:theFullRecord.creators];
    
    
    
    /* old code: we don't show publisher anymore
    NSMutableString* details_cat = [NSMutableString new];
    if ([theFullRecord.edition length]>0) {
        [details_cat appendString:theFullRecord.edition];
        if ([theFullRecord.publisher length]>0) {
            [details_cat appendFormat:@"\n%@",theFullRecord.publisher];
        }
    } else {
        //since full_record.edition is empty here, we can proceed with only publisher
        [details_cat appendString:theFullRecord.publisher];
    }
    self.detailsLabel.text = details_cat;
     */
}

-(void)fetchCoverUrl:(NSString*)coverUrl
{
    bool is_ipad = RD_IS_IPAD;
    
    NSString* resize_url = [InfoGalleriImageUrlUtils getResizedImageUrl:coverUrl
                                                                toWidth:is_ipad ? 166 :  65
                                                               toHeight:is_ipad ? 255 : 105
                                                           usingQuality:8
                                                               withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX
                                                           outputFormat:@"jpeg"
                                                      doubleUpForRetina:YES];
    
    //was: [LazyLoadImageView createLazyLoaderWithView:self.bookCoverImageView url:[NSURL URLWithString:resize_url] animationTime:0.2 delegate:nil];
    [[LazyLoadManager instance] lazyLoadUIImageFromUrl:resize_url
                                     setScaleforRetina:YES
                                             onSuccess:^(UIImage *image) {
                                                 [self setCoverImageAspectRatioConstraintForSize:image.size];
                                                 self.bookCoverImageView.alpha=0;
                                                 self.bookCoverImageView.image = image;
                                                 [UIView animateWithDuration:0.2
                                                                  animations:^{
                                                                      self.bookCoverImageView.alpha=1;
                                                                  }];
                                                 
                                             }
                                               onError:^(LazyLoaderErrorCode errorCode, NSString *errorMessage) {
                                                   //no need
                                               }
     ];
}


-(void)setCoverImageAspectRatioConstraintForSize:(CGSize)size{
    if(mCoverImageAspectRatioConstraint != nil){
        [self.bookCoverImageView removeConstraint:mCoverImageAspectRatioConstraint];
    }
    
    mCoverImageAspectRatioConstraint = [NSLayoutConstraint constraintWithItem:self.bookCoverImageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.bookCoverImageView attribute:NSLayoutAttributeHeight multiplier:size.width/size.height constant:0];
    mCoverImageAspectRatioConstraint.priority = UILayoutPriorityDefaultHigh;
    [self.bookCoverImageView addConstraint:mCoverImageAspectRatioConstraint];
    [self.view layoutIfNeeded];
}


//TODO: Maybe rename this function
- (IBAction)reserveButtonClicked:(id)sender
{
    if([[BAPatronSettings instance] isUserAllowedIMFEditorAccessForCurrentLibrary]) {
#ifdef BA_IMF_BUILD
        //IMF editing handler
        [[IMFPackageEditManager instance] attemptAddRemoveToPackage:theRecord
                                                        didAddBlock:^(void) {
                                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                                [self.reserveButton setTitle:@"FJERN" forState:UIControlStateNormal];
                                                            });
                                                            
                                                        }
                                                     didRemoveBlock:^(void) {
                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                             [self.reserveButton setTitle:@"TILFØJ" forState:UIControlStateNormal];
                                                         });
                                                     }];
#endif
        
    } else {
        //normal reserve button handler
        if (theFullRecord != nil && theFullRecord.availability != nil) {
            [self performReservationFromAvailability:theFullRecord.availability];
        } else {
            BAAvailability* availability = [[BACoverUrlAndAvailabilityMemoryCache instance] getAvailabilityForIdentifier:theRecord.identifier];
            if (availability != nil) {
                [self performReservationFromAvailability:availability];
            }
        }
    }
}

-(void)performReservationFromAvailability:(BAAvailability*)availability
{
    if (availability.isReservable && [availability.reservationId length]>0) {
        [BAAddReservationViewController createAddReservationDialogWithReservationId:availability.reservationId title:theRecord.title];
    }
}

- (IBAction)goToEResourceButtonClicked:(id)sender {
    BAWebBrowserViewController* webBrowser = [BAWebBrowserViewController new];
    [webBrowser setUrl:theFullRecord.eRessourceUrl];
    [self.navigationController presentViewController:webBrowser animated:YES completion:nil];
}

-(void)showRelatedList
{
    if (relatedMaterialsTableViewController==nil) {
        //relatedMaterialsTableViewController = [BARelatedMaterialsTableViewController new];
        if (RD_IS_IPAD) {
            relatedMaterialsTableViewController = [[BARelatedMaterialsTableViewController alloc] initWithNibName:@"BARelatedMaterialsTableViewController_iPad" bundle:nil];
        } else {
            relatedMaterialsTableViewController = [[BARelatedMaterialsTableViewController alloc] initWithNibName:@"BARelatedMaterialsTableViewController_iPhone" bundle:nil];
        }

        [self addChildViewController:relatedMaterialsTableViewController];
    }
    if (recordDetailsViewController!=nil) {
        [recordDetailsViewController.view removeFromSuperview];
    }
    [self.tabSwitchViewView addSubview:relatedMaterialsTableViewController.view];
    [BAUtils setViewToFillParent:relatedMaterialsTableViewController.view];
}

-(void)showRecordDetails
{
    if (recordDetailsViewController==nil) {
        recordDetailsViewController = [BAAbstractViewController new];
        [self addChildViewController:recordDetailsViewController];
        /* already done
        if (theFullRecord!=nil) {
            [recordDetailsViewController setFullRecord:theFullRecord];
        }
         */
    }
    if (relatedMaterialsTableViewController!=nil) {
        [relatedMaterialsTableViewController.view removeFromSuperview];
    }
    [self.tabSwitchViewView addSubview:recordDetailsViewController.view];
    [BAUtils setViewToFillParent:recordDetailsViewController.view];
}

-(void)handleNewCoverUrls:(id)sender
{
    BACoverUrl* coverUrl = [[BACoverUrlAndAvailabilityMemoryCache instance] getCoverUrlForIdentifier:theRecord.identifier];
    if (coverUrl != nil) {
        [self fetchCoverUrl:coverUrl.url];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_COVER_URL_CACHE_COVER_URLS_ARRIVED object:nil];
    }
}

#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

@end
